package com.molyfun.parents.activity.common;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.molyfun.parents.utils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:3/15/17.
 */

public class BaseFileDownloadActivity extends BaseActivity {

    private static final int IEP_DOWNLOAD_FINISH = 333;
    private static final int IEP_CONNEXT_TIMEOUT = 334;//超时
    private static final int IEP_FIEL_INVALID = 335;//文件无效

    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            dismissProgressDialog();
            switch (msg.what) {
                case IEP_DOWNLOAD_FINISH:
                    try {
                        openFile((String) msg.obj);
                    } catch (Exception e) {
                        e.printStackTrace();
                        toast("未找到打开文件的应用程序");
                    }
                    break;
                case IEP_CONNEXT_TIMEOUT:
                    toast("请检查网络连接");
                    break;
                case IEP_FIEL_INVALID:
                    toast("文件无效");
                    break;
            }
        }
    };

    protected void downloadFeil(final String serverpath, final String name) {

        showProgressDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(serverpath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        File file = new File(FileUtils.IEP_FIEL_PATH);
                        if (!file.exists()) {
                            file.mkdir();
                        }
                        File f = new File(FileUtils.IEP_FIEL_PATH, name);
                        if (f.exists()) {
                            f.delete();
                        }
                        FileOutputStream fos = new FileOutputStream(f);
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                            fos.flush();
                        }
                        fos.close();
                        is.close();
                        Message msg = new Message();
                        msg.what = IEP_DOWNLOAD_FINISH;
                        msg.obj = f.getPath();
                        mHandler.sendMessage(msg);
                    } else {
                        mHandler.sendEmptyMessage(IEP_CONNEXT_TIMEOUT);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(IEP_FIEL_INVALID);
                }
            }
        }).start();

    }

    protected void openFile(String filePath) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        //获取文件file的MIME类型
        String type = getMIMEType(filePath);
        //设置intent的data和Type属性。
        intent.setDataAndType(Uri.fromFile(new File(filePath)), type);
        //跳转
        startActivity(intent);
    }

    protected String getMIMEType(String filePath) {
        String type = "";
        String end = filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase();
        if (TextUtils.isEmpty(end)) return type;
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    protected static final String[][] MIME_MapTable = {
            //{后缀名，MIME类型}
            {"ppt", "application/vnd.ms-powerpoint"},
            {"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {"pdf", "application/pdf"},
            {"doc", "application/msword"},
            {"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {"xls", "application/vnd.ms-excel"},
            {"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}
    };


}
